package com.system.vote.admin.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.vote.admin.entity.TVote;
import com.system.vote.admin.entity.TVoteDetail;
import com.system.vote.admin.entity.TVoteItem;
import com.system.vote.admin.entity.TWxUserinfo;
import com.system.vote.admin.security.JwtUtil;
import com.system.vote.admin.service.TVoteDetailService;
import com.system.vote.admin.service.TVoteItemService;
import com.system.vote.admin.service.TVoteService;
import com.system.vote.admin.service.TWxUserinfoService;
import com.system.vote.common.utils.StringUtils;
import com.system.vote.core.customBean.PageBean;
import com.system.vote.core.http.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/app/vote/tvote")
@Api(tags = "App投票列表管理")
public class AppTVoteController {

    @Autowired
    private TVoteService tVoteService;

    @Autowired
    private TVoteItemService tVoteItemService;

    @Autowired
    private TWxUserinfoService tWxUserinfoService;

    @Autowired
    private TVoteDetailService tVoteDetailService;


    @PostMapping("/listOfUser")
    public Result listOfUser(@RequestHeader String token, @RequestBody PageBean pageBean) {
        Claims claims = JwtUtil.parseJWT(token);
        String uid = claims.getId();
        String query = pageBean.getQuery();
        Page<TVote> pageResult = tVoteService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()),
                new LambdaQueryWrapper<TVote>()
                        .eq(TVote::getUserid, uid)
                        .and(e -> e.eq(TVote::getStatus, "0"))
                        .like(StringUtils.isNotEmpty(query), TVote::getTitle, query)
                        .orderByDesc(TVote::getVoteEndTime));

        List<TVote> listData = pageResult.getRecords();
        for (TVote tvote : listData
        ) {
            List<TVoteDetail> tVoteDetailList = tVoteDetailService.list(new LambdaQueryWrapper<TVoteDetail>().eq(TVoteDetail::getWUid, uid)
                    .and(e -> e.eq(TVoteDetail::getVoteId, tvote.getId())));
            tvote.setTVoteDetailList(tVoteDetailList);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", listData);
        resultMap.put("total", pageResult.getTotal());
        return Result.success(resultMap);
    }

    @PostMapping("/listOfJoinUser")
    public Result listOfJoinUser(@RequestHeader String token, @RequestBody PageBean pageBean) {
        Claims claims = JwtUtil.parseJWT(token);
        String uid = claims.getId();
        String query = pageBean.getQuery();
        Page<TVote> pageResult = tVoteService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()),
                new QueryWrapper<TVote>()
                        .eq("status", "0")
                        .like(StringUtils.isNotEmpty(query), "title", query).inSql("id", "select vote_id from t_vote_detail where w_uid=" + uid)
                        .orderByDesc("vote_end_time"));

        List<TVote> listData = pageResult.getRecords();
        for (TVote tvote : listData
        ) {
            List<TVoteDetail> tVoteDetailList = tVoteDetailService.list(new LambdaQueryWrapper<TVoteDetail>().eq(TVoteDetail::getWUid, uid)
                    .and(e -> e.eq(TVoteDetail::getVoteId, tvote.getId())));
            tvote.setTVoteDetailList(tVoteDetailList);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", listData);
        resultMap.put("total", pageResult.getTotal());
        return Result.success(resultMap);
    }

    @PostMapping("/listAll")
    public Result listAll(@RequestHeader String token, @RequestBody PageBean pageBean) {
        Claims claims = JwtUtil.parseJWT(token);
        String uid = claims.getId();
        String query = pageBean.getQuery();
        String voteFinishType = pageBean.getVoteFinishType();
        LambdaQueryWrapper<TVote> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isEmpty(voteFinishType)) {
            lambdaQueryWrapper
                    .eq(TVote::getStatus, "0")
                    .like(StringUtils.isNotEmpty(query), TVote::getTitle, query)
                    .orderByDesc(TVote::getVoteEndTime);
        } else if (Objects.equals(voteFinishType, "1")) {//进行中
            lambdaQueryWrapper
                    .eq(TVote::getStatus, "0")
                    .and(e -> e.ge(TVote::getVoteEndTime, new Date()))
                    .like(StringUtils.isNotEmpty(query), TVote::getTitle, query)
                    .notInSql(TVote::getId, "select vote_id from t_vote_detail where w_uid=" + uid)
                    .orderByDesc(TVote::getVoteEndTime);
        } else if (Objects.equals(voteFinishType, "2")) {//已投票
            lambdaQueryWrapper
                    .eq(TVote::getStatus, "0")
                    .like(StringUtils.isNotEmpty(query), TVote::getTitle, query)
                    .inSql(TVote::getId, "select vote_id from t_vote_detail where w_uid=" + uid)
                    .orderByDesc(TVote::getVoteEndTime);
        } else if (Objects.equals(voteFinishType, "3")) {//已结束
            lambdaQueryWrapper
                    .eq(TVote::getStatus, "0")
                    .and(e -> e.le(TVote::getVoteEndTime, new Date()))
                    .like(StringUtils.isNotEmpty(query), TVote::getTitle, query)
                    .notInSql(TVote::getId, "select vote_id from t_vote_detail where w_uid=" + uid)
                    .orderByDesc(TVote::getVoteEndTime);
        }
        Page<TVote> pageResult = tVoteService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()), lambdaQueryWrapper
        );

        List<TVote> listData = pageResult.getRecords();
        if (StringUtils.isEmpty(voteFinishType) || Objects.equals(voteFinishType, "2")) {
            for (TVote tvote : listData
            ) {
                List<TVoteDetail> tVoteDetailList = tVoteDetailService.list(new LambdaQueryWrapper<TVoteDetail>().eq(TVoteDetail::getWUid, uid)
                        .and(e -> e.eq(TVoteDetail::getVoteId, tvote.getId())));
                tvote.setTVoteDetailList(tVoteDetailList);
            }

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", listData);
        resultMap.put("total", pageResult.getTotal());
        return Result.success(resultMap);
    }


    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id) {
        TVote tVote = tVoteService.getById(id);
        TWxUserinfo tWxUserinfo = tWxUserinfoService.getOne(new QueryWrapper<TWxUserinfo>().eq("id", tVote.getUserid()));
        tVote.setTWxUserinfo(tWxUserinfo);
        List<TVoteItem> items = tVoteItemService.list(new QueryWrapper<TVoteItem>().eq("vote_id", tVote.getId()));
        tVote.setItems(items);
        Map<String, Object> map = new HashMap<>();
        map.put("objData", tVote);
        return Result.success(map);
    }

    @GetMapping("/delete/{id}")
    @Transactional
    public Result delete(@PathVariable Long id) {
        tVoteDetailService.remove(new QueryWrapper<TVoteDetail>().eq("vote_id", id));
        tVoteItemService.remove(new QueryWrapper<TVoteItem>().eq("vote_id", id));
        tVoteService.removeById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("flag", true);
        return Result.success(map);
    }

    @PostMapping("/checkTitle")
    public Result checkTitle(@RequestBody TVote tVote) {
        if (tVoteService.getTVoteByTitle(tVote.getTitle()) == null) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    @Transactional
    @PostMapping("/save")
    public Result saveVote(@RequestBody TVote tVote) throws ParseException {
        System.out.println("tvote:" + tVote);
        System.out.println(tVote.getVoteEndTime());
        tVote.setStatus("0");
        tVote.setCreateTime(new Date());
        Long voteId = tVoteService.getTVoteAutoId(tVote);
        Collection<TVoteItem> tVoteItems = new ArrayList<>();
        for (TVoteItem tVoteItem : tVote.getItems()
        ) {
            tVoteItem.setVoteId(voteId);
            tVoteItem.setNumber(0L);
            tVoteItems.add(tVoteItem);
        }

        tVoteItemService.saveBatch(tVoteItems);
        Map<String, Object> map = new HashMap<>();
        map.put("flag", true);
        return Result.success(map);
    }

    @PostMapping("/updateVoteStatus")
    public Result updateVoteStatus(@RequestBody TVote tVote) {
        TVote currentTVote = tVoteService.getById(tVote.getId());
        currentTVote.setStatus(tVote.getStatus());
        tVoteService.updateById(currentTVote);
        String msg = "";
        if (Objects.equals(tVote.getStatus(), "0")) {
            msg = "启用投票栏目成功";
        } else {
            msg = "禁用投票栏目成功";
        }
        return Result.success(msg);
    }

    @GetMapping("/getUserListByItemId/{vId}/{itemId}/{pageNum}/{pageSize}")
    public Result getUserListByItemId(@RequestHeader String token, @PathVariable("vId") Long vId, @PathVariable("itemId") Long itemId, @PathVariable("pageNum") Long pageNum, @PathVariable("pageSize") Long pageSize) {
        Claims claims = JwtUtil.parseJWT(token);
        String uid = claims.getId();
        Page<TWxUserinfo> pageResult = tWxUserinfoService.page(
                new Page<>(pageNum,
                        pageSize),
                new QueryWrapper<TWxUserinfo>()
                        .select("id", "nick_name", "avatar_url", "last_login_date", "status", "register_date", "phone", "email")
                        .inSql("id", "SELECT w_uid FROM t_vote_detail WHERE vote_item_id=" + itemId)
                        .orderByDesc("last_login_date"));

        List<TWxUserinfo> tWxUserinfoList = pageResult.getRecords();

        for (TWxUserinfo user : tWxUserinfoList
        ) {
            TVoteDetail tVoteDetail = tVoteDetailService.getOne(new LambdaQueryWrapper<TVoteDetail>()
                    .eq(TVoteDetail::getWUid, user.getId())
                    .and(e -> e.eq(TVoteDetail::getVoteId, vId))
                    .and(e -> e.eq(TVoteDetail::getVoteItemId, itemId)));
            user.setTVoteDetail(tVoteDetail);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", tWxUserinfoList);
        resultMap.put("total", pageResult.getTotal());
        return Result.success(resultMap);
    }
}

